<?php
declare (strict_types = 1);

namespace app\model;

/**
 * 用户模型
 */
class User extends BaseModel
{
    /**
     * 表名
     * @var string
     */
    protected $name = 'user';
    
    /**
     * 字段映射
     * @var array
     */
    protected $schema = [
        'id' => 'int',
        'username' => 'string',
        'password' => 'string',
        'nickname' => 'string',
        'email' => 'string',
        'mobile' => 'string',
        'avatar' => 'string',
        'status' => 'int',
        'create_time' => 'datetime',
        'update_time' => 'datetime',
        'delete_time' => 'datetime',
    ];
    
    /**
     * 验证规则
     * @var array
     */
    protected $rules = [
        'username' => 'require|min:3|max:20',
        'password' => 'require|min:6|max:20',
        'email' => 'email',
        'mobile' => 'mobile',
    ];
    
    /**
     * 验证消息
     * @var array
     */
    protected $messages = [
        'username.require' => '用户名不能为空',
        'username.min' => '用户名长度不能小于3个字符',
        'username.max' => '用户名长度不能大于20个字符',
        'password.require' => '密码不能为空',
        'password.min' => '密码长度不能小于6个字符',
        'password.max' => '密码长度不能大于20个字符',
        'email.email' => '邮箱格式不正确',
        'mobile.mobile' => '手机号格式不正确',
    ];
    
    /**
     * 写入前处理密码
     * @param array $data
     * @return array
     */
    public static function onBeforeInsert($data)
    {
        if (isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        return $data;
    }
    
    /**
     * 更新前处理密码
     * @param array $data
     * @return array
     */
    public static function onBeforeUpdate($data)
    {
        if (isset($data['password'])) {
            $data['password'] = password_hash($data['password'], PASSWORD_DEFAULT);
        }
        return $data;
    }
    
    /**
     * 验证用户密码
     * @param string $password 密码
     * @param string $hash 数据库中的密码哈希
     * @return bool
     */
    public static function verifyPassword(string $password, string $hash): bool
    {
        return password_verify($password, $hash);
    }
}